package org.bean.alios.iot;

import com.aliyun.openservices.iot.api.Profile;
import com.aliyun.openservices.iot.api.message.MessageClientFactory;
import com.aliyun.openservices.iot.api.message.api.MessageClient;
import com.aliyun.openservices.iot.api.message.callback.MessageCallback;
import com.aliyun.openservices.iot.api.message.entity.Message;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.iot.model.v20180120.PubRequest;
import com.aliyuncs.iot.model.v20180120.PubResponse;
import com.aliyuncs.iot.model.v20180120.SetDevicePropertyRequest;
import com.aliyuncs.iot.model.v20180120.SetDevicePropertyResponse;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.RandomStringUtils;
import org.bean.alios.iot.config.MyConfig;
import org.bean.alios.iot.entity.ReceiveMessage;
import org.json.JSONObject;
import org.springframework.boot.WebApplicationType;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.annotation.Bean;

import static org.bean.alios.iot.config.MyConfig.accessKey;

@ServletComponentScan
@SpringBootApplication
@Slf4j
public class Appliction extends SpringBootServletInitializer {

    @Bean
    public void h2Client() throws Exception {
        // 连接配置
        Profile profile = Profile.getAccessKeyProfile(MyConfig.endPoint, MyConfig.regionId,
                accessKey, MyConfig.accessSecret);
        // 构造客户端
        MessageClient client = MessageClientFactory.messageClient(profile);
        //
        DefaultProfile.addEndpoint(MyConfig.regionId, MyConfig.regionId,
                MyConfig.product, MyConfig.domain);
        IClientProfile clientProfile = DefaultProfile.getProfile(MyConfig.regionId, MyConfig.accessKey,
                MyConfig.accessSecret);
        DefaultAcsClient acsClient = new DefaultAcsClient(clientProfile);
        PubRequest request = new PubRequest();
        request.setProductKey(MyConfig.productKey);
        //
        ReceiveMessage receiveMessage = new ReceiveMessage();
        JSONObject jsonResponse = new JSONObject();
        // 数据接收
        client.connect(messageToken -> {
            Message receice = messageToken.getMessage();
            log.info("receive message from : " + receice);
            byte[] playload = receice.getPayload();
            String jsonString = "";
            JSONObject jsonRecevice = null;
            try {
                jsonString = new String(playload, "UTF-8");
                log.info("payload : " + jsonString);
                // 接收参数，获取参数值
                jsonRecevice = new JSONObject(jsonString);
                receiveMessage.setImei(jsonRecevice.getLong("IMEI"));
                receiveMessage.setDevicename(jsonRecevice.getString("DeviceName"));
                receiveMessage.setMessage(jsonRecevice.getString("Message"));
                StringBuilder builder = new StringBuilder();
                builder.append(" IMEI : " + receiveMessage.getImei());
                builder.append(" DeviceName : " + receiveMessage.getDevicename());
                builder.append(" Message : " + receiveMessage.getMessage());
                log.info("receive message data : " + builder.toString());
                // 回复参数设置
                jsonResponse.put("IMEI", receiveMessage.getImei());
                jsonResponse.put("DeviceName", receiveMessage.getDevicename());
                jsonResponse.put("Result" , "R_OK");
                jsonResponse.put("Code", RandomStringUtils.randomAlphanumeric(20));
                log.info("publish message : " + jsonResponse.toString());
                //
                request.setMessageContent(Base64.encodeBase64String(jsonResponse.toString().getBytes()));
                request.setTopicFullName(MyConfig.topic);
                request.setQos(0); //目前支持QoS0和QoS1
                PubResponse response = acsClient.getAcsResponse(request);
                log.info("response requestId :" + response.getRequestId() + " success : " + response + " error message : "
                        + response.getErrorMessage());
            }
            catch (Exception ex) {
                ex.printStackTrace();
            }
            return MessageCallback.Action.CommitSuccess;
        });
    }

    /**
     *
     * @param args
     */
    public static void main(String[] args) {
        SpringApplicationBuilder application = new SpringApplicationBuilder(Appliction.class);
        application.web(WebApplicationType.SERVLET);
        application.run(args);
    }
}
